package com.cycling.app.view;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import java.util.Locale;


/**
 * Created by LiZhanPing onShrinkScreen 2016/9/23.
 */

public class CountDownView extends android.support.v7.widget.AppCompatTextView {

    private static final int TIME_MILLIS = 60 * 1000;

    private TimeCounter mTimeCounter;
    private boolean mCountStart = false;
    private boolean mCountFinish = true;

    private OnCountDownFinishListener mListener;

    public CountDownView(Context context) {
        this(context, null);
    }

    public CountDownView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountDownView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setClickable(true);
        setText(String.format(Locale.getDefault(), "%d秒后开始计费，请检查车辆", TIME_MILLIS));

        mTimeCounter = new TimeCounter(TIME_MILLIS, 1000);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        start();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mTimeCounter != null) {
            mTimeCounter.cancel();
            mTimeCounter = null;
        }
    }

    private void start() {
        if (mTimeCounter != null)
            mTimeCounter.start();
    }

    public boolean isStarted() {
        return mCountStart;
    }

    public boolean isFinished() {
        return mCountFinish;
    }

    private class TimeCounter extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public TimeCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (!mCountStart) mCountStart = true;
            if (mCountFinish) mCountFinish = false;
            setText(String.format(Locale.getDefault(), "%d秒后开始计费，请检查车辆", millisUntilFinished / 1000));  //设置倒计时时间
        }

        @Override
        public void onFinish() {
            mCountFinish = true;
            mCountStart = false;
            if (mListener != null) {
                mListener.onFinish();
            }
        }
    }

    public void setOnCountDownFinishListener(OnCountDownFinishListener listener) {
        mListener = listener;
    }

    public interface OnCountDownFinishListener {
        void onFinish();
    }

}
